package com.runen.infinitemovement.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.GetTopIdEntity;
import com.runen.infinitemovement.model.entity.UserEntity;
import com.runen.infinitemovement.tool.AppUtils;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.widget.popupwind.CommonDialog;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.LogUtil;
import com.runen.rxnetlibrary.utils.StringUtil;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.net.shoot.sharetracesdk.AppData;
import cn.net.shoot.sharetracesdk.ShareTrace;
import cn.net.shoot.sharetracesdk.ShareTraceInstallListener;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.tv_long_discrible)
    TextView tvLongDiscrible;
    @BindView(R.id.edt_input_phone)
    EditText edtInputPhone;
    @BindView(R.id.v_line)
    View vLine;
    @BindView(R.id.edt_input_code)
    EditText edtInputCode;
    @BindView(R.id.tv_code)
    TextView tvCode;
    @BindView(R.id.rl_code)
    RelativeLayout rlCode;
    @BindView(R.id.v_line2)
    View vLine2;
    @BindView(R.id.tv_send_login)
    TextView tvSendLogin;
    @BindView(R.id.ll_user_agreement)
    LinearLayout llUserAgreement;
    @BindView(R.id.tv_user_agreement)
    TextView tvUserAgreement;
    @BindView(R.id.tv_privacy_agreement)
    TextView tvPrivacyAgreement;
    @BindView(R.id.cb_user_agreement)
    CheckBox cbUserAgreement;
    private AuthCountDownTimer timeCount;
    private boolean isPuse;
    private String targetId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        timeCount = new AuthCountDownTimer(60 * 1000, 1000);
        edtInputPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                int edtSize = edtInputPhone.getText().toString().intern().length();
                if (isPuse) {

                } else if (edtSize < 11) {
                    tvCode.setBackground(CommonUtil.getDrawable(R.drawable.bg_btn_fa5438_dp6_alpha));
                    tvCode.setEnabled(false);
                } else {
                    tvCode.setBackground(CommonUtil.getDrawable(R.drawable.bg_btn_fa5438_dp6));
                    tvCode.setEnabled(true);
                }
                int edtSize2 = edtInputCode.getText().toString().intern().length();
                if (edtSize2 < 4 || edtSize < 11) {
                    tvSendLogin.setBackground(CommonUtil.getDrawable(R.drawable.bg_fa5438_f63d5b_dp360_alpha));
                    tvSendLogin.setEnabled(false);
                } else {
                    tvSendLogin.setBackground(CommonUtil.getDrawable(R.drawable.bg_fa5438_f63d5b_dp360));
                    tvSendLogin.setEnabled(true);
                }
            }
        });

        edtInputCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                int edtSize = edtInputCode.getText().toString().intern().length();
                if (edtSize < 4) {
                    tvSendLogin.setBackground(CommonUtil.getDrawable(R.drawable.bg_fa5438_f63d5b_dp360_alpha));
                    tvSendLogin.setEnabled(false);
                } else {
                    tvSendLogin.setBackground(CommonUtil.getDrawable(R.drawable.bg_fa5438_f63d5b_dp360));
                    tvSendLogin.setEnabled(true);
                }
            }
        });
    }


    @OnClick({R.id.tv_code, R.id.tv_send_login, R.id.tv_user_agreement, R.id.tv_privacy_agreement})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_code:
                getCode();
                break;
            case R.id.tv_send_login:
                if (!cbUserAgreement.isChecked()) {
                    ToastUtils.showShort("请先同意用户协议以及隐私政策");
                    return;
                }
                tvSendLogin.setEnabled(false);
                onLogin();
                break;
            case R.id.tv_user_agreement:
                Intent intent = new Intent(this, WebActivity.class);
                intent.putExtra("LINK_URL", Constant.USER_AGREEMENT);
                intent.putExtra("flag", 1);
                startActivity(intent);
                break;
            case R.id.tv_privacy_agreement:
                Intent intent2 = new Intent(this, WebActivity.class);
                intent2.putExtra("LINK_URL", Constant.PRIVACY_AGREEMENT);
                intent2.putExtra("flag", 2);
                startActivity(intent2);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        ShareTrace.getInstallTrace(new ShareTraceInstallListener() {
            @Override
            public void onInstall(AppData data) {
                LogUtil.e("ShareTrace", data.toString() + "");
                targetId = data.getParamsData();
            }

            @Override
            public void onError(int code, String msg) {
                Log.e("ShareTrace", "Get install trace info error. code=" + code + ",msg=" + msg);
            }
        });
    }

    /**
     * 登录
     */
    private void onLogin() {
        UserAPI.clearLogin();
        String phone = edtInputPhone.getText().toString().trim();
        String code = edtInputCode.getText().toString().trim();
        if (!StringUtil.isMobileNo(phone)) {
            Toast.makeText(LoginActivity.this, "请输入正确的手机号码", Toast.LENGTH_SHORT);
            return;
        }
        if (TextUtils.isEmpty(code) || code.length() < 4) {
            Toast.makeText(LoginActivity.this, "请输入验证码", Toast.LENGTH_SHORT);
            return;
        }
        Map<String, String> object = new HashMap<>();
        object.put("grant_type", "mobile_code");
        object.put("mobile", phone);
        object.put("validCode", code);
        if (!TextUtils.isEmpty(targetId)) {
            object.put("targetId", targetId);
        }
        showDialog();
        new UserAPI().onLogin(object, new BaseResultCallback<UserEntity>() {
            @Override
            public void onResponse(UserEntity response) {
                dismissDialog();
                tvSendLogin.setEnabled(true);
                if (response.code == 0) {
                    UserAPI.saveUserInfo(response);
                    userRegId();
                    //判断人员加入部门的状态（0未申请 1审批中 2通过 3拒绝）

                    if (response.isNew) {
                        Intent intent = new Intent(LoginActivity.this, ImprovePersonalDataActivity.class);
//                        intent.putExtra("userIcon", userIcon);
                        intent.putExtra("inTenant", response.inTenant);
                        startActivity(intent);
                    } else if (response.inTenant == 0) {
                        startActivity(new Intent(LoginActivity.this, InputTeamCodeActivity.class));
                    } else if (response.inTenant == 1) {
                        Intent intent = new Intent(LoginActivity.this, InputTeamCodeActivity.class);
                        intent.putExtra("BranchCheck", 1);
                        startActivity(intent);
                        finish();
                    } else if (response.inTenant == 2) {
                        AppUtils.jumpToMain(LoginActivity.this);
                    } else if (response.inTenant == 3) {
                        ToastUtils.showShort("请重新选择部门");
                        startActivity(new Intent(LoginActivity.this, InputTeamCodeActivity.class));
                    } else if (response.inTenant == 4) {
                        topId();
                    } else if (response.inTenant == 5) {
                        CommonDialog dialog = CommonDialog.getInstance(LoginActivity.this,
                                "您已被队长踢出团队，加入新团队重新踏上征途吧~");
                        dialog.setCancelable();
                        dialog.setOnClickListener(new CommonDialog.OnClickListener() {
                            @Override
                            public void onSendListener() {
                                topId();
                            }

                            @Override
                            public void onDismiss() {

                            }
                        });
                    }
                    edtInputCode.setText("");
                } else {
                    ToastUtils.showShort(response.msg);
                }
            }

            @Override
            public void onError(Throwable e, String body) {
                super.onError(e, body);
                tvSendLogin.setEnabled(true);
            }
        });
    }

    private void topId() {
        showDialog();
        new UserAPI().getTopId(new BaseResultCallback<GetTopIdEntity>() {
            @Override
            public void onResponse(GetTopIdEntity response) {
                dismissDialog();
                if (response.code == 0) {
                    if (!TextUtils.isEmpty(response.data)) {
                        Intent intent = new Intent(LoginActivity.this, CheckTeamActivity.class);
                        intent.putExtra("companyId", response.data);
                        startActivity(intent);
                    }
                }
            }

            @Override
            public void onError(Throwable e, String body) {
                super.onError(e, body);
                dismissDialog();
            }
        });
    }

    private void userRegId() {
        JSONObject object = new JSONObject();
        String regId = JPushInterface.getRegistrationID(this);
        LogUtil.e("regId", regId);
        Log.e("regId", "userRegId: " + regId);
        if (!TextUtils.isEmpty(regId)) {
            try {
                object.put("channelId", regId);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        new UserAPI().onUserRegId(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                if (response.getCode() != 0) {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        });
    }

    /**
     * 获取验证码
     */
    private void getCode() {
        timeCount.start();
        String phone = edtInputPhone.getText().toString();
        if (!StringUtil.isMobileNo(phone)) {
            Toast.makeText(LoginActivity.this, "请输入正确的手机号码", Toast.LENGTH_SHORT);
            return;
        }
        JSONObject object = new JSONObject();
        try {
            object.put("phone", phone);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new UserAPI().getPhoneSMS(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                if (response.getCode() == 0) {
                    isPuse = true;
//                    ToastUtils.showLong("");
                    Toast.makeText(LoginActivity.this, "验证码已发送到你的手机", Toast.LENGTH_SHORT);
                } else {
                    isPuse = false;
                    ToastUtils.showShort(response.getMessage());
                    tvCode.setEnabled(true);
                    tvCode.setBackground(CommonUtil.getDrawable(R.drawable.bg_btn_fa5438_dp6));
                    tvCode.setText(R.string.login_get_code);
                }
            }
        });

    }

    @Override
    protected boolean isUseFullScreenMode() {
        return false;
    }


    private class AuthCountDownTimer extends CountDownTimer {
        private AuthCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tvCode.setBackground(CommonUtil.getDrawable(R.drawable.bg_btn_fa5438_dp6_alpha));
            tvCode.setText(String.format("%3ds", millisUntilFinished / 1000));
            tvCode.setEnabled(false);
            isPuse = true;
        }

        @Override
        public void onFinish() {
            tvCode.setEnabled(true);
            tvCode.setBackground(CommonUtil.getDrawable(R.drawable.bg_btn_fa5438_dp6));
            tvCode.setText(R.string.login_get_code);
            isPuse = false;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBusEntity event) {
        switch (event.getMsg()) {
            case 4:
                finish();
                break;
            default:
                break;
        }
    }
}
